package com.hyj.ecp.backstage.goods.action;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ecp.goods.GoodsQO;
import com.ecp.goods.GoodsTrait;
import com.hyj.ecp.common.constant.SysConstant;
import com.hyj.util.JsonUtil;

@Controller
@RequestMapping("/backstage/test/*")
public class Test {
	Log logger = LogFactory.getLog(Test.class);
	
	
	@RequestMapping(value="add.do")
	public Object add(GoodsQO qo){
		System.out.println("       add.do   ---------   "+qo.getLogo());
		System.out.println(qo.getImgs().length+"       add.do   ---------   "+qo.getImgs()[0]);
		return qo;
	}
	
	@RequestMapping(value="upload.do")
	public void doupload(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String,Object> vo = new HashMap<String,Object>();
        
		
		 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();     
         // 设置最多只允许在内存中存储的数据,单位:字节   
         diskFileItemFactory.setSizeThreshold(1024*1024);   
         ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);  
       //设置上传文件大小的上限，-1表示无上限 
         upload.setSizeMax(15*1024*1024);
         upload.setHeaderEncoding("UTF-8");   
         //开始读取上传信息   
         String name ="";
         long size = 0;
         
         List<FileItem> fileItems;
		 try {
		    fileItems = upload.parseRequest(request);
			
			Iterator<FileItem> iter = fileItems.iterator();
	      while(iter.hasNext()){
            FileItem item = iter.next();
			if (!item.isFormField()) {
				name = item.getName();
				size = item.getSize();
				String path =SysConstant.getPropertiy("imagePath");
				String extPath = "";
				
				File uploadDir = new File(path);
		    	if(!uploadDir.isDirectory()){
		    		throw new Exception ("上传目录不存在。");
		    	}
		    	
		    	//检查目录写权限
		    	if(!uploadDir.canWrite()){
		    		throw new Exception ("上传目录没有写权限。");
		    	}
		    	
		    	//创建文件夹 image file flash 
		    	//path += "image" + "/";
		    	extPath += "image" + "/";
		    	
		    	File saveDirFile = new File(path);
		    	if (!saveDirFile.exists()) {
		    		saveDirFile.mkdirs();
		    	}
		    	
		    	//创建年份文件夹
		    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		    	String year = sdf.format(new Date());
		    	//path += year + "/";
		    	extPath += year + "/";
		    	
		    	File yeardirFile = new File(path);
		    	if (!yeardirFile.exists()) {
		    		yeardirFile.mkdirs();
		    	}
				
				//创建文件夹  子文件夹  日期
		    	sdf = new SimpleDateFormat("yyyyMMdd");
		    	String ymd = sdf.format(new Date());
		    	//path += ymd + "/";
		    	extPath += ymd + "/";
		    	
		    	path = path +extPath;
		    	
				File parent = new File(path);
				if(!parent.isDirectory()){  
					  parent.mkdirs();
		         }
				File f = new File(path, name);
				item.write(f);
				
				System.out.println(name+" -----------------------   "+size);
				
				
				vo.put("error", 0);
				vo.put("url", extPath+name);
			}else{
				//获得formdate     
	            String fieldName = item.getFieldName();   
	                  //获得简单域的值    
                String fieldValue = item.getString("UTF-8");   
                logger.info(fieldName+" -->>："+fieldValue);  
			}
		  }
			} catch (Exception e) {
				e.printStackTrace();
				vo.put("error", 1);
				vo.put("msg", e.getMessage());
			}
		
		
	    String json = JsonUtil.toJson(vo, false);
		logger.info("返回参数：" + json);
		response.setContentType("text/html; charset=UTF-8");
		OutputStream out  = response.getOutputStream();;
		
		out.write(json.getBytes("UTF-8"));
		out.flush();
		out.close();
	}
	
	
	public static void main(String ... args){
		Random r = new Random(4);
	    for(int i=0;i<10;i++){
	    	
	    	System.out.println(r.nextInt(2));
	    }
	}
}
